package com.jiangyifen.robot.sdkserver.requesthandler;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.jiangyifen.robot.consts.ErrCode;
import com.jiangyifen.robot.sdk.request.Authentication;
import com.jiangyifen.robot.sdk.request.RequestName;
import com.jiangyifen.robot.sdk.response.BaseResponse;

import io.netty.channel.ChannelHandlerContext;

@Component
public class AuthenticationHandler extends AbstractRequestHandler<Void>{

	@Value("${robot_sdk_server_secretkey}")
	private String sceretKeyServer;
	
	@Override
	public String requestName() {
		return RequestName.authentication;
	}
	
	@Override
	public BaseResponse<Void> handle(ChannelHandlerContext ctx, String requestId, String requestBody) {
		try {
			Authentication body = JSON.parseObject(requestBody, Authentication.class);
			String secretKeyClient = body.getSceretKey();
			if(secretKeyClient==null){
				return BaseResponse.FAIL(requestId, null,ErrCode.AUTHENTICATION_FAIL.getErrcode(),ErrCode.AUTHENTICATION_FAIL.getErrmsg());
			}
			if(secretKeyClient.equals(sceretKeyServer)){
				return BaseResponse.SUCCESS(requestId, null);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return BaseResponse.FAIL(requestId, null,"-1",e.getMessage());
		}
		return BaseResponse.FAIL(requestId, null,ErrCode.AUTHENTICATION_FAIL.getErrcode(),ErrCode.AUTHENTICATION_FAIL.getErrmsg());
	}

}
